package com.ksana.context.support;

import com.ksana.bean.factory.config.ConfigurableListableBeanFactory;
import com.ksana.bean.factory.support.DefaultListableBeanFactory;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext {
    private DefaultListableBeanFactory beanFactory;

    private String[] configLocations;

    @Override
    protected void refreshBeanFactory() {
        this.beanFactory = new DefaultListableBeanFactory();
        loadBeanDefinitions(this.beanFactory);
    }

    public void setConfigLocations(String configLocation) {
        setConfigLocations(new String[]{configLocation});
    }

    public void setConfigLocations(String... configLocations) {
        this.configLocations = new String[configLocations.length];
        for (int i = 0; i < configLocations.length; i++) {
            this.configLocations[i] = configLocations[i];
        }
    }

    protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory);

    protected String[] getConfigLocations() {
        return this.configLocations != null ? this.configLocations : getDefaultConfigLocations();
    }

    protected String[] getDefaultConfigLocations() {
        return null;
    }

    @Override
    protected void closeBeanFactory() {
        DefaultListableBeanFactory beanFactory = this.beanFactory;
        if (beanFactory != null) {
            this.beanFactory = null;
        }
    }

    @Override
    public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
        DefaultListableBeanFactory beanFactory = this.beanFactory;

        if (beanFactory == null) {
            throw new IllegalStateException("工厂没有被初始化或者已经被关闭了");
        }

        return beanFactory;
    }
}
